<template>
  <div class="Confirm-order">
    <van-nav-bar
      title="确认订单"
      left-text="返回"
      left-arrow
      fixed
      @click-left="back"
    />

    <div class="order-box">
      <div class="select-address">
        <div class="select-title">
          <div @click="showPopup">选择地址</div>
          <div><van-icon name="arrow" /></div>
        </div>
        <div class="user-box">
          <div class="user-info">
            <div class="user-name">{{ selectAddress.name }}</div>
            <div class="user-phone">{{ selectAddress.tel }}</div>
            <div class="user-default" v-show="selectAddress.isDefault">
              <van-tag mark color="#0c34ba">默认</van-tag>
            </div>
          </div>
          <div class="user-address">{{ selectAddress.address }}</div>
        </div>
      </div>

      <div class="order-conent">
        <div class="o-title">订单信息</div>
        <div>
          <div
            class="o-pro-item"
            v-for="(item, index) in productData"
            :key="index"
          >
            <ProList class="not-padding" :isHasCheckbox="false" :proData="item">
              <div class="o-count">x{{ item.count }}</div>
            </ProList>
          </div>
        </div>
        <div class="o-bottom">
          <div class="empty-round">
            <div class="round-box left-r"></div>
            <div class="round-box right-r"></div>
          </div>
          <div class="o-count-price">
            <div class="o-c1">共计{{ total }}件</div>
            <div class="o-c2">
              总价:<span>&yen;{{ money }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="pay">
        <van-button color="linear-gradient(to right, #b6e1fe, #0c34ba)" @click="pay" block round
          >立即结算</van-button
        >
      </div>
    </div>

    <!-- 选择地址列表 -->
    <van-popup v-model="show" position="bottom" closeable>
      <div class="address-list">
        <van-address-list
          v-model="chosenAddressId"
          @select="select"
          default-tag-text="默认"
          
          :list="list"
          @add="goNewAddress"
          @edit="goNewAddress"
        />
      </div>
    </van-popup>

    <!-- 密码键盘弹出层 -->
    <van-popup v-model="showPay" position="bottom">
      <!-- 密码框 -->
      <div class="pay-password">
        <div class="passowrd-title">支付密码</div>
        <van-password-input v-model="payPassword" :focused="showKeyboard" />
        <!-- 数字键盘 -->
        <van-number-keyboard 
        v-model="payPassword" 
        :show="showKeyboard" 
        @input="watchNumber"
        />
      </div>
    </van-popup>
  </div>
</template>

<script>
import ProList from "../components/ProList.vue";
export default {
  name: "ConfirmOrder",
  components: {
    ProList,
  },
  data() {
    return {
      //商品sids
      sids: [],
      //需要购买的数据
      productData: [],
      //订单商品总共数量
      total: 0,
      //支付密码
      payPassword:'',
      //数字输入框
      showKeyboard:true,

      //订单总金额
      money: 0,
      //地址遮罩层
      show: false,

      //显示支付密码
      showPay:false,

      //支付密码
      userPayPassword:"123456",

      //选择地址(默认地址)
      selectAddress: {},

      list: [],
      chosenAddressId: "",
    };
  },
  created() {
    //截取sids
    this.sids = this.$route.query.sids.split("-");
    //   console.log("this.sids",this.sids);
    let sids = JSON.stringify(this.sids);
    //   console.log("sids",sids);

    this.getProductBySids(sids);

    this.getUserAddressData();
  },
  methods: {
    //返回上一级
    back() {
      this.$router.go(-1);
    },
    //获取用户地址数据
    getUserAddressData() {
      let tokenString = sessionStorage.getItem("token");

      this.axios({
        method: "get",
        url: "/findAddress",
        params: {
          tokenString,
        },
      })
        .then((res) => {
          // console.log("获取用户地址数据", res);
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);
            return;
          }

          if (res.data.code === 20000) {
            res.data.result.forEach((v) => {
              v.isDefault = Boolean(v.isDefault);
              v.address = `${v.province}${v.city}${v.county}${v.addressDetail}`;

              if (v.isDefault) {
                this.selectAddress = { ...v };
                this.chosenAddressId = v.id;
              }
            });
            this.list = res.data.result;

            // console.log("this.selectAddress ==> ", this.selectAddress);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //根据商品sids获取数据
    getProductBySids(sids) {
      let tokenString = sessionStorage.getItem("token");

      this.axios({
        method: "get",
        url: "/commitShopcart",
        params: {
          tokenString,
          sids,
        },
      })
        .then((res) => {
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);
            return;
          }

          if (res.data.code === 50000) {
            if (res.data.result.length === 0) {
              //如果没有商品, 默认跳转到购物袋页面
              return this.$router.push({ name: "Shopbag" });
            }
            //个数
            let total = 0;
            //价格
            let money = 0;
            res.data.result.forEach((v) => {
              total += v.count;
              money += v.count * v.price;
            });

            this.total = total;
            this.money = money.toFixed(2);
            this.productData = res.data.result;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //弹出选择地址列表层
    showPopup() {
      this.show = true;
    },
    //弹出支付密码层
    ShowPay(){
      this.showPay = true
    },
    //跳转到新增地址或者编辑地址页面
    goNewAddress(item) {
      if (item) {
        this.$router.push({ name: "NewAddress", params: { aid: item.aid } });

        // console.log(item.aid);
      } else {
        this.$router.push({ name: "NewAddress" });
      }
    },
    //选择地址
    select(item) {
      if (this.chosenAddressId === item.id) {
        return;
      }
      this.chosenAddressId = item.id;
      this.selectAddress = { ...item };
      this.show = false;
    },
    //提交订单
    pay(){
      //判断是否选择地址
      if(!this.chosenAddressId){
         this.$toast("请选择地址");
        return;
      }

      //二次确认
      this.$dialog.confirm({
        title:'确认订单',
        message:'是否确认订单?'
      }).then(()=>{
        //确认
        this.showPay = true
      }).catch(err=>{
        console.log(err);
      })
    },
    //密码验证
    watchNumber(value){
      let inputPassword = this.payPassword+value;

      if(inputPassword.length===6){
        //如果密码正确
        if(inputPassword===this.userPayPassword){
          this.showPay = true;

          let tokenString = sessionStorage.getItem("token");

          let sids = JSON.stringify(this.sids);

          //获取联系人信息
          let data = {
            phone:this.selectAddress.tel,
            name:this.selectAddress.name,
            address:this.selectAddress.address,
            tokenString,
            sids
          };

          this.axios({
            method:'post',
            url:'/pay',
            data
          }).then(res=>{
            // console.log(res);
            if (res.data.code == 700) {
                //用户未登录, 拦截操作, 通知用户去登录
                this.$toast("请先登录");
                setTimeout(() => {
                  this.$router.push({ name: "Login" });
                }, 2000);

                return;
              }
              this.$toast(res.data.msg);

              if(res.data.code===60000){

                //修改购物车数量
                this.$root.publicShopbagCount -= this.total;

                //跳转我的订单页面
                setTimeout(() => {
                  this.$router.push({name: 'Order'});
                }, 2000)
              }
          }).catch(err=>{
            console.log(err);
          })
        }else{
          //提示密码错误
          this.$toast("支付密码错误");
        }
      }
    }
  },
};
</script>

<style lang="less" scoped>
.Confirm-order {
  padding-top: 46px;
  padding-bottom: 54px;
  //   background-color: red;
}
.order-conent {
  margin-top: 10px;
  padding: 10px;
  background-color: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}
.o-title {
  padding-bottom: 10px;
  font-size: 14px;
}
.o-pro-item {
  margin-bottom: 10px;
}
.o-bottom {
  padding: 10px 0 0;
  margin-top: 20px;
  border-top: 1px dashed #e8e8e8;
  position: relative;
}
.empty-round {
  position: absolute;
  left: 0;
  top: -8px;
  height: 16px;
  width: 100%;
  display: flex;
}
.o-count-price {
  display: flex;
  align-items: center;
}
.o-c2 {
  font-size: 14px;
  color: #0c34ba;
  font-weight: bold;
}
.o-c1 {
  margin-right: auto;
  font-size: 14px;
  color: #666;
}
.pay {
  position: fixed;
  left: 0;
  bottom: 10px;
  right: 0;
  padding: 0 10px;
}
.select-title {
  display: flex;
}
/deep/.van-icon-arrow {
  top: 3px;
}
.order-box {
  padding: 10px;
}
.select-address {
  padding: 10px;
  background-color: #fff;
  font-size: 14px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}
.user-box {
  margin-top: 10px;
}
.user-info {
  display: flex;
  align-items: center;
  .user-name {
    font-weight: bold;
    color: #0c34ba;
  }
  .user-phone {
    padding: 0 10px;
  }
}
.user-address {
  color: #666;
  margin-top: 5px;
}
.address-list {
  padding: 15px 10px 10px;
}
/deep/ .van-address-list {
  padding: 15px 0 60px;
}
.pay-password {
  padding: 50px 10px 254px;
}
.passowrd-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #666;
}
/deep/.van-tag .van-tag--mark .van-tag--default{
  border-color: #0c34ba;
    background-color: #0c34ba;
}
 /deep/ .van-nav-bar .van-icon {
    color: #0c34ba;
  }

  /deep/ .van-nav-bar__text {
    color: #0c34ba;
  }

  /deep/ .van-address-item .van-radio__icon--checked .van-icon {
    border-color: #0c34ba;
    background-color: #0c34ba;
  }

  /deep/ .van-tag--danger {
    background-color: #0c34ba;
  }

  /deep/ .van-button--danger {
    border-color: #0c34ba;
    background-color: #0c34ba;
  }

</style>